package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.entity.SysMenu;
import net.qhzw.vip.qiyu.entity.SysRole;
import net.qhzw.vip.qiyu.mapper.SysMenuMapper;
import net.qhzw.vip.qiyu.service.SysMenuService;
import net.qhzw.vip.qiyu.service.SysRoleService;
import net.qhzw.vip.qiyu.service.SysUserService;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {


    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysUserService sysUserService;

    /***
     * 根据userId获取权限数据
     * @param userId
     * @return
     */
    @Override
    public List<String> getPermissions(Long userId) {
        String roleCode = sysRoleService.getRoleCodeByUserId(userId);
        List<String> permissions = null;
        if ("ROLE_ADMIN".equals(roleCode)) {
            //所有权限
            permissions = sysMenuMapper.getPermissionsAll();
        } else {
            permissions = sysMenuMapper.getPermissionByUserId(userId);
        }
        //去重
        return permissions.stream().distinct().collect(Collectors.toList());
    }

    /****
     * 通过用户的id 查询用户的菜单数据
     * @param userId
     * @return
     */
    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        //如果该用户是超级管理员->>拥有所有的菜单
        if (sysRoleService.isSuperAdmin(userId)) {
            return list(); //查询所以菜单数据
        }
        //如果该用户不是超级管理员->>查询角色->查询菜单
        return sysMenuMapper.selectMenusByUserId(userId);
    }

    /***
     * 查询全部菜单
     * @return
     */
    @Override
    public List<SysMenu> findList(Long userId) {
        List<SysMenu> list = null;
        SysRole role = sysRoleService.getRoleByUserId(userId);
        if (role != null && role.getCode().equals("ROLE_ADMIN")) {
            list = list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, 1));
        }else {
            list = sysMenuMapper.findListByShopId(role.getId());
        }
        //全部数据
//        List<SysMenu> list = list(new LambdaQueryWrapper<SysMenu>()
//                .eq(SysMenu::getStatus, 1));
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        //一级菜单
        List<SysMenu> rootMenu = list.stream().filter(sysMenu ->
                sysMenu.getParentId() == null || sysMenu.getParentId() == 0)
                .collect(Collectors.toList());

        //查询所以的二级菜单
        for (SysMenu rootmenu : rootMenu) {
            rootmenu.setChilds(getChildMenus(rootmenu.getId(), list));
        }
        Collections.sort(rootMenu, new Comparator<SysMenu>() {
            @Override
            public int compare(SysMenu o1, SysMenu o2) {
                return o1.getSort() - o2.getSort();
            }
        });
        return rootMenu;
    }

    /**
     * 查询菜单的子菜单 (递归)
     *
     * @param parentId 父菜单的ID
     * @return
     */
    private List<SysMenu> getChildMenus(Long parentId, List<SysMenu> sources) {
        List<SysMenu> childs = new ArrayList<>();
        for (SysMenu source : sources) {
            if (source.getParentId().equals(parentId)) { // 找儿子
                childs.add(source);
                source.setChilds(getChildMenus(source.getId(), sources)); // 给该儿子设置儿子
            }
        }
        return childs;
    }

    /***
     * 添加菜单
     * @param sysMenu
     * @return
     */
    @Override
    public boolean addMenu(SysMenu sysMenu) {
        //log.info("添加菜单", JSON.toJSONString(sysMenu, true));
        SysMenu sysMenudb = addUserInfo(sysMenu);
        return save(sysMenudb);
    }

    /***
     * 修改菜单
     * @param sysMenu
     * @return
     */
    @Override
    public boolean updateMenu(SysMenu sysMenu) {
        //log.info("修改菜单", JSON.toJSONString(sysMenu, true));
        sysMenu.setLastUpdateTime(new Date());
        sysMenu.setModifyBy(SecurityUtils.getUserId());
        return updateById(sysMenu);
    }

    /***
     * 查询根节点count
     * @param id
     * @return
     */
    @Override
    public int findChildCount(Long id) {
        return sysMenuMapper.findChildCount(id);
    }

    /***
     * 根据id逻辑删除
     * @param id
     * @return
     */
    @Override
    public boolean tombstone(Long id) {
        SysMenu sysMenu = new SysMenu();
        sysMenu.setId(id);
        sysMenu.setStatus((byte) 0);
        return updateById(sysMenu);
    }


    private SysMenu addUserInfo(SysMenu sysMenu) {
        sysMenu.setId(IdWorker.getId());
        sysMenu.setCreateBy(SecurityUtils.getUserId());
        sysMenu.setModifyBy(SecurityUtils.getUserId());
        sysMenu.setCreated(new Date());
        sysMenu.setLastUpdateTime(new Date());
        sysMenu.setStatus((byte) 1);
        return sysMenu;
    }

}
